package com.gxnu.edu.cn.ttxxt.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gxnu.edu.cn.ttxxt.entity.FontSettings;
import com.gxnu.edu.cn.ttxxt.entity.Users;
import com.gxnu.edu.cn.ttxxt.mapper.FontSettingRepository;
import com.gxnu.edu.cn.ttxxt.mapper.UserRepository;
import com.gxnu.edu.cn.ttxxt.service.FontSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class FontSettingServiceImpl implements FontSettingService {

    @Autowired
    private FontSettingRepository fontSettingRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    @Transactional
    public FontSettings addFontSetting(Long userId, String fontFamily, Integer fontSize,
                                       String fontColor, String fontWeight, String fontStyle,
                                       boolean isDefault) {
        // 验证用户存在
        Users users = userRepository.selectById1(userId);
        System.out.println(users.getUserId());
        if (users == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        // 检查是否已存在相同配置
        QueryWrapper<FontSettings> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("font_family", fontFamily)
                .eq("font_size", fontSize)
                .eq("font_color", fontColor)
                .eq("font_weight", fontWeight)
                .eq("font_style", fontStyle);

        // 如果已存在，返回现有配置
        FontSettings existingSettings = fontSettingRepository.selectOne(queryWrapper);
        if (existingSettings != null) {
            System.out.println("相同字体设置已存在: " + existingSettings.getFontSettingId());
            return existingSettings;
        }

        // 如果是默认设置，先取消其他默认设置
        if (isDefault) {
            UpdateWrapper<FontSettings> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("user_id", userId)
                    .set("is_default", 0);
            fontSettingRepository.update(null, updateWrapper);
        }

        // 创建新字体设置
        FontSettings fontSettings = new FontSettings();
        fontSettings.setUserId(userId);
        fontSettings.setFontFamily(fontFamily);
        fontSettings.setFontSize(fontSize);
        fontSettings.setFontColor(fontColor);
        fontSettings.setFontWeight(fontWeight);
        fontSettings.setFontStyle(fontStyle);
        fontSettings.setIsDefault(isDefault ? 1 : 0);
        fontSettings.setCreateTime(new Date()); // 设置创建时间
        fontSettings.setUpdateTime(new Date());

        // 使用insert方法而不是update
        fontSettingRepository.updatefontSettings(fontSettings);
        System.out.println("字体设置成功："+fontSettings.toString());
        return fontSettings;
    }

    @Override
    @Transactional
    public FontSettings updateFontSetting(Long fontSettingId, String fontFamily, Integer fontSize,
                                          String fontColor, String fontWeight, String fontStyle,
                                          boolean isDefault) {
        FontSettings fontSettings = fontSettingRepository.selectById(fontSettingId);
        if (fontSettings == null) {
            throw new IllegalArgumentException("字体设置不存在");
        }

        // 检查是否已存在相同配置（排除自己）
        QueryWrapper<FontSettings> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", fontSettings.getUserId())
                .eq("font_family", fontFamily)
                .eq("font_size", fontSize)
                .eq("font_color", fontColor)
                .eq("font_weight", fontWeight)
                .eq("font_style", fontStyle)
                .ne("font_setting_id", fontSettingId);

        if (fontSettingRepository.selectCount(queryWrapper) > 0) {
            throw new IllegalArgumentException("相同的字体设置已存在");
        }

        // 如果是默认设置，先取消其他默认设置
        if (isDefault && fontSettings.getIsDefault() == 0) {
            UpdateWrapper<FontSettings> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("user_id", fontSettings.getUserId())
                    .set("is_default", 0);
            fontSettingRepository.update(null, updateWrapper);
        }

        // 更新字体设置
        fontSettings.setFontFamily(fontFamily);
        fontSettings.setFontSize(fontSize);
        fontSettings.setFontColor(fontColor);
        fontSettings.setFontWeight(fontWeight);
        fontSettings.setFontStyle(fontStyle);
        fontSettings.setIsDefault(isDefault ? 1 : 0);
        fontSettings.setUpdateTime(new Date());

        fontSettingRepository.updateById(fontSettings);
        return fontSettings;
    }

    @Override
    @Transactional
    public void deleteFontSetting(Long fontSettingId) {
        FontSettings fontSettings = fontSettingRepository.selectById(fontSettingId);
        if (fontSettings == null) {
            throw new IllegalArgumentException("字体设置不存在");
        }

        // 如果是默认设置，需要先设置其他为默认
        if (fontSettings.getIsDefault() == 1) {
            QueryWrapper<FontSettings> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", fontSettings.getUserId())
                    .ne("font_setting_id", fontSettingId)
                    .orderByAsc("create_time")
                    .last("LIMIT 1");

            FontSettings newDefault = fontSettingRepository.selectOne(queryWrapper);
            if (newDefault != null) {
                newDefault.setIsDefault(1);
                fontSettingRepository.updateById(newDefault);
            }
        }

        fontSettingRepository.deleteById(fontSettingId);
    }

    @Override
    public FontSettings getUserFontSettings(Long userId) {
//        QueryWrapper<FontSettings> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("user_id", userId)
//                .orderByDesc("is_default")
//                .orderByAsc("create_time");

        return fontSettingRepository.selectByUserId(userId);
    }

    @Override
    public FontSettings getDefaultFontSetting(Long userId) {
        QueryWrapper<FontSettings> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("is_default", 1);

        return fontSettingRepository.selectOne(queryWrapper);
    }

    @Override
    @Transactional
    public void setDefaultFontSetting(Long userId, Long fontSettingId) {
        FontSettings fontSettings = fontSettingRepository.selectById(fontSettingId);
        if (fontSettings == null || !fontSettings.getUserId().equals(userId)) {
            throw new IllegalArgumentException("字体设置不存在或不属于该用户");
        }

        if (fontSettings.getIsDefault() == 1) {
            return; // 已经是默认设置
        }

        // 取消其他默认设置
        UpdateWrapper<FontSettings> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId)
                .set("is_default", 0);
        fontSettingRepository.update(null, updateWrapper);

        // 设置新的默认
        fontSettings.setIsDefault(1);
        fontSettings.setUpdateTime(new Date());
        fontSettingRepository.updateById(fontSettings);
    }
}